//
//  LoginViewController.swift
//  ShopIOS
//
//  Created by Apple on 2019/7/17.
//  Copyright © 2019 Apple. All rights reserved.
//

import UIKit

class LoginViewController: UIViewController {

    @IBOutlet weak var tf_username: UITextField!
    @IBOutlet weak var tf_pwd: UITextField!
    @IBOutlet weak var btn_login: UIButton!
    @IBOutlet weak var lb_register: UILabel!
    @IBOutlet weak var lb_chage_way: UILabel!
    @IBOutlet weak var iv_check: UIImageView!
    @IBOutlet weak var lb_check: UILabel!
    @IBOutlet weak var lb_agreement: UILabel!
    @IBOutlet weak var uv_pwd: UIView!
    @IBOutlet weak var uv_code: UIView!
    @IBOutlet weak var tf_code: UITextField!
    @IBOutlet weak var btn_getcode: UIButton!
    var name=""
    var pwd=""
    var code=""
    var getUserResult:GetUserResult!
    var way=0//密码登录0 验证码登录1
    var flag=0//选中协议0 未选中协议1
    
    var remainingSeconds: Int = 0 {
        willSet {
            btn_getcode.setTitle("\(newValue)秒后重新获取", for: .normal)
            
            if newValue <= 0 {
                btn_getcode.setTitle("重新获取验证码", for: .normal)
                isCounting = false
            }
        }
    }
    var countdownTimer: Timer?
    var isCounting = false {
        willSet {
            if newValue {
                countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime(timer:)), userInfo: nil, repeats: true)
                
                remainingSeconds = 60
            } else {
                countdownTimer?.invalidate()
                countdownTimer = nil
                
            }
            
            btn_getcode.isEnabled = !newValue
        }
    }
    @objc func updateTime(timer: Timer) {
        // 计时开始时，逐秒减少remainingSeconds的值
        remainingSeconds -= 1
    }
    @objc func sendButtonClick(sender: UIButton) {
        name=tf_username.text!
        if name.isEmpty {
            HUD.showText("请输入用户名！")
            return
        }
        //发送验证码
        validateUsername()
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        btn_login.layer.cornerRadius=5
        
        btn_login.addOnClickListener(target: self, action:#selector(login))
        iv_check.addOnClickListener(target: self, action:#selector(check))
        lb_check.addOnClickListener(target: self, action:#selector(check))
        lb_agreement.addOnClickListener(target: self, action:#selector(toAgreeMent))
        
        lb_register.addOnClickListener(target: self, action:#selector(toRegister))
        lb_chage_way.addOnClickListener(target: self, action:#selector(change_way))
        btn_getcode.addOnClickListener(target: self, action:#selector(sendButtonClick(sender:)))
        // Do any additional setup after loading the view.
    }
    @objc func check(){
        if flag==0{
            iv_check.image=UIImage(named: "check_false")
            flag=1
        }else{
            iv_check.image=UIImage(named: "check_true")
            flag=0
        }
    }
    @objc func change_way(){
        if way==0{
            lb_chage_way.text="密码登录>"
            uv_pwd.isHidden=true
            uv_code.isHidden=false
            way=1
        }else{
            lb_chage_way.text="短信验证码登录>"
            uv_pwd.isHidden=false
            uv_code.isHidden=true
            way=0
        }
    }
    @objc func back(){
        self.navigationController?.popViewController(animated: true)
    }
    @objc func toRegister(){
        self.navigationController?.pushViewController(RegisterViewController(), animated: true)
    }
    @objc func toAgreeMent(){
        self.navigationController?.pushViewController(UIWebViewViewController(headtitle: "用户协议", url: "http://mall.xigyu.com/m-Wap/Article/YSZC/20"), animated: true)
    }
    @objc func login(){
        name=tf_username.text!
        pwd=tf_pwd.text!
        code=tf_code.text!
        if flag == 1{
            HUD.showText("请阅读并同意用户协议！")
            return
        }
        if name.isEmpty {
            HUD.showText("请输入用户名！")
            return
        }
        if way==0{
            if pwd.isEmpty {
                HUD.showText("请输入密码！")
                return
            }
        }else{
            if code.isEmpty {
                HUD.showText("请输入验证码！")
                return
            }
        }
        getTokenByUserid()
    }
    @objc func getUser(){
        var d = ["userName":name,
                 "password":pwd,
                 "app_key":app_key,
                 "timestamp":getTimestamp()
            ] as [String : String]
        let sign=SignTopRequest(params: d)
        d["sign"]=sign
        AlamofireHelper.get(url: GetUser, parameters: d, successHandler: {[weak self](res)in
            HUD.dismiss()
            guard let ss = self else {return}
            ss.getUserResult=GetUserResult.init(json: res)
            if ss.getUserResult.Success=="true"{
                HUD.showText("登录成功！")
                UserDefaults.standard.set(ss.getUserResult.UserKey, forKey: "UserKey")
                UserDefaults.standard.set(ss.name, forKey: "UserID")
                userkey=UserDefaults.standard.string(forKey: "UserKey")
                UserID=UserDefaults.standard.string(forKey: "UserID")
                NotificationCenter.default.post(name: NSNotification.Name("loginOk"), object: nil)
                ss.back()
            }else{
                HUD.showText(ss.getUserResult.ErrorMsg!)
            }
        }){[weak self] (error) in
            HUD.dismiss()
            guard let ss = self else {return}
        }
    }
    @objc func loginon(){
        var d = ["userName":name,
                 "passWord":pwd,
                 "RoleType":"10"//角色类型 5平台 6工厂 7师傅 8商城 10代表包含5678
            ] as [String : String]
        AlamofireHelper.post(url: LoginOn, parameters: d, successHandler: {[weak self](res)in
            HUD.dismiss()
            guard let ss = self else {return}
            if res["Data"]["Item1"].boolValue{
                UserDefaults.standard.set(res["Data"]["Item2"].stringValue, forKey: "adminToken")
                adminToken=UserDefaults.standard.string(forKey: "adminToken")
                if (ss.way==0){
                    ss.getUser()
                }else {
                    ss.getUserWithoutPassword()
                }
            }else{
                HUD.showText(res["Data"]["Item2"].stringValue)
            }
        }){[weak self] (error) in
            HUD.dismiss()
            guard let ss = self else {return}
        }
    }
    
    @objc func addAndUpdatePushAccount(){
        var d = ["userName":name,
                 "password":pwd,
                 "app_key":app_key,
                 "timestamp":getTimestamp()
            ] as [String : String]
        AlamofireHelper.get(url: AddAndUpdatePushAccount, parameters: d, successHandler: {[weak self](res)in
            HUD.dismiss()
            guard let ss = self else {return}
            
        }){[weak self] (error) in
            HUD.dismiss()
            guard let ss = self else {return}
        }
    }
    @objc func getTokenByUserid(){
        let d = ["userID":name] as [String : String]
        AlamofireHelper.post(url: GettokenbyUserid, parameters: d, successHandler: {[weak self](res)in
            HUD.dismiss()
            guard let ss = self else {return}
            if res["Data"]["Item2"].stringValue.isEmpty{//已经登录过了，后台存有token
                ss.loginon()
            }else{
                UserDefaults.standard.set(res["Data"]["Item2"].stringValue, forKey: "adminToken")
                adminToken=UserDefaults.standard.string(forKey: "adminToken")
                if (ss.way==0){
                    ss.getUser()
                }else {
                    ss.getUserWithoutPassword()
                }
            }
        }){[weak self] (error) in
            HUD.dismiss()
            guard let ss = self else {return}
        }
    }
    @objc func getPhoneCode(){
        var d = ["contact":name,
                 "app_key":app_key,
                 "timestamp":getTimestamp()
            ] as [String : String]
        let sign=SignTopRequest(params: d)
        d["sign"]=sign
        AlamofireHelper.get(url: GetPhoneCode, parameters: d, successHandler: {[weak self](res)in
            HUD.dismiss()
            guard let ss = self else {return}
            if res["success"].boolValue{
                HUD.showText("验证码已发送，请注意查收")
                // 启动倒计时
                ss.isCounting = true
            }else{
                HUD.showText(res["msg"].stringValue)
            }
        }){[weak self] (error) in
            HUD.dismiss()
            guard let ss = self else {return}
        }
    }
    @objc func getUserWithoutPassword(){
        var d = ["checkCode":code,
                 "contact":name,
                 "app_key":app_key,
                 "timestamp":getTimestamp()
            ] as [String : String]
        let sign=SignTopRequest(params: d)
        d["sign"]=sign
        AlamofireHelper.get(url: GetUserWithoutPassword, parameters: d, successHandler: {[weak self](res)in
            HUD.dismiss()
            guard let ss = self else {return}
            ss.getUserResult=GetUserResult.init(json: res)
            if ss.getUserResult.Success=="true"{
                HUD.showText("登录成功！")
                UserDefaults.standard.set(ss.getUserResult.UserKey, forKey: "UserKey")
                UserDefaults.standard.set(ss.name, forKey: "UserID")
                userkey=UserDefaults.standard.string(forKey: "UserKey")
                UserID=UserDefaults.standard.string(forKey: "UserID")
                NotificationCenter.default.post(name: NSNotification.Name("loginOk"), object: nil)
                ss.back()
            }else{
                HUD.showText(ss.getUserResult.ErrorMsg!)
            }
        }){[weak self] (error) in
            HUD.dismiss()
            guard let ss = self else {return}
        }
    }
    @objc func validateUsername(){
        let d = ["UserID":name] as [String : String]
        AlamofireHelper.post(url: ValidateUserName, parameters: d, successHandler: {[weak self](res)in
            HUD.dismiss()
            guard let ss = self else {return}
            if res["Data"].boolValue{
                HUD.showText("该账号未注册")
            }else{
                ss.getPhoneCode()
            }
        }){[weak self] (error) in
            HUD.dismiss()
            guard let ss = self else {return}
        }
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
